import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/pay_type_model.dart';
import 'package:flutter_deer/res/colors.dart';

class SortDragListDialog extends StatefulWidget {
  final String title;
  final List<PayTypeModel> items;
  final Function(List<PayTypeModel>) onConfirmed;
  final VoidCallback? onCancel; // 新增：取消回调

  const SortDragListDialog({
    Key? key,
    required this.title,
    required this.items,
    required this.onConfirmed,
    this.onCancel, // 新增参数
  }) : super(key: key);

  @override
  State<SortDragListDialog> createState() => _SortDragListDialogState();
}

class _SortDragListDialogState extends State<SortDragListDialog> {
  late List<PayTypeModel> _items; // 新增：用于拖拽排序的items副本

  @override
  void initState() {
    super.initState();
    _items = widget.items.map((item) => PayTypeModel.fromJson(item.toJson())).toList();
  }

  // 处理取消操作
  void _handleCancel() {
    if (widget.onCancel != null) {
      widget.onCancel!(); // 调用自定义取消回调
    } else {
      // 默认行为：尝试pop，如果失败则不执行任何操作
      Navigator.maybePop(context);
    }
  }

  // 新增：交换items中两个元素的位置
  void _swapItems(int oldIndex, int newIndex) {
    setState(() {
      if (newIndex > oldIndex) {
        newIndex -= 1;
      }
      final item = _items.removeAt(oldIndex);
      _items.insert(newIndex, item);
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return AlertDialog(
      backgroundColor: Colours.bg,
      title: Row(
        children: [
          Expanded(child: Text(widget.title)),
        ],
      ),
      content: SizedBox(
        width: 340,
        height: screenSize.height * 0.5,
        child: _buildDraggableList(), // 原有：构建普通列表
      ),
      actions: [
        TextButton(
          onPressed: _handleCancel, // 使用新的取消处理方法
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () => {
            Navigator.maybePop(context),
            widget.onConfirmed(_items)
          },
          child: const Text('确认'),
        ),
      ],
    );
  }

  // 新增：构建可拖拽列表
  Widget _buildDraggableList() {
    return ReorderableListView(
      onReorder: _swapItems,
      shrinkWrap: true,
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      // 添加内边距
      physics: const ClampingScrollPhysics(),
      children: [
        for (int index = 0; index < _items.length; index++)
          SizedBox(
            key: ValueKey(_items[index]),
            child: _buildDraggableListItem(index),
          ),
      ],
    );
  }

  // 新增：构建可拖拽列表项
  Widget _buildDraggableListItem(int index) {
    final PayTypeModel item = _items[index];
    return SizedBox(
      key: ValueKey(item.id),
      child: InkWell(
        onTap: () {
          setState(() {
            item.switchConsumePay = !item.switchConsumePay;
          });
        },
        child: Card(
          margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
          shadowColor: Colors.red.withOpacity(0.2),
          elevation: 4,
          child: Row(
            children: [
              // 右侧选择框
              Checkbox(
                value: item.switchConsumePay,
                onChanged: (value) {
                  print('index:$index hashcode:${value.hashCode} value:${value} click:$item');
                  setState(() {
                    item.switchConsumePay = !item.switchConsumePay;
                    print('--->index:$index hashcode:${value.hashCode} value:${value} click:$item');
                  });
                },
              ),
              // 中间文本
              Expanded(
                child: Text(
                  '${item.paymentName}',
                  style: const TextStyle(fontSize: 16),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
